// UserRecover.js
import copyicon from '@/assets/image/copyicon.png';
import ROBOT_AVATAR from '@/assets/image/space-avatar.png';
import zancaiicon from '@/assets/image/zancaiicon.png';
import { search_feedback } from '@/services/ant-design-pro/conversation';
import { DislikeFilled, LikeFilled } from '@ant-design/icons';
import { Button, Dropdown, message, Modal, Tag, Tooltip } from 'antd';
import ClipboardJS from 'clipboard';
import { nanoid } from 'nanoid';
import { useEffect, useRef, useState } from 'react';
import { connect } from 'umi';
const dayjs = require('dayjs');
const MiniModelArticle = (props: any) => {
  const [list, setList] = useState([]);
  // const [currentIndex, setCurrentIndex] = useState(0);
  const {
    data = [],
    scrollToBottom = () => {},
    updateState = ({}) => {},
    setAILogs = ({}) => {},
  } = props;
  const modalBodyRef = useRef<any>(null);
  const [isDemoOpen, setIsDemoOpen] = useState(false);
  const [currentDemo, setCurrentDemo] = useState(null); //当前示例
  const splitContent = (content: any, limit = 300) => {
    const truncatedContent = content.slice(0, limit);
    // 使用换行符 '\n' 分割截取后的文本
    const paragraphs = truncatedContent.split('\n').filter((p) => p.trim() !== ''); // 过滤掉空段落
    // 只包装前三个段落
    const firstThreeParagraphs = paragraphs.slice(0, 3);
    // 使用 map 函数将段落包装在 <p> 标签中
    const formattedContent = firstThreeParagraphs
      .map((p: any, index: any) => {
        if (index === firstThreeParagraphs.length - 1) {
          // 最后一个段落添加 class="ptwo"
          return `<p class="ptwo">${p}</p>`;
        }
        return `<p>${p}</p>`;
      })
      .join(''); // 将包装后的文本段落拼接成一个字符串

    return formattedContent;
  };
  useEffect(() => {
    if (data && data.length > 0) {
      //处理数据
      let ls: any = [];
      data.forEach((item: any) => {
        let newObj = {
          ...item,
          key: nanoid(),
          source: item.source,
          subject: item.subject,
          detail: item.detail,
          title: item.title,
          domain: item.domain,
          main_body: item.main_body,
          content: splitContent(item.main_body),
        };
        ls.push(newObj);
      });
      // setList(ls);
      // 使用 setTimeout 逐个添加数据
      const addDataWithDelay = (index: any) => {
        if (index < ls.length) {
          setTimeout(() => {
            setList((prevList: any) => [...prevList, ls[index]]);
            addDataWithDelay(index + 1); // 递归调用以添加下一条数据
            scrollToBottom('', 6);
          }, 800); // 间隔一秒添加一条数据
        }
      };
      // 启动添加数据的过程
      addDataWithDelay(0);
    }
  }, [data]);
  // useEffect(() => {
  //   if (data.length > 0) {
  //     setList([data[0]]);
  //   }
  // }, [data]);

  const lookSource = (data: any) => {
    setIsDemoOpen(true);
    setCurrentDemo(data);
    //滚动到高亮位置
    setTimeout(() => {
      const highlightElement = modalBodyRef.current.querySelector('.highlightCon');
      if (highlightElement) {
        highlightElement.scrollIntoView({
          behavior: 'smooth',
          block: 'start',
        });
      }
    }, 200);
  };
  //关闭示例
  const demoModalCancel = () => {
    setIsDemoOpen(false);
  };
  //拷贝文字
  const copyText = (textToCopy: any) => {
    const clipboard = new ClipboardJS('.copy-button', {
      text: () => textToCopy.sentence,
    });

    clipboard.on('success', () => {
      message.open({
        type: 'info',
        content: '拷贝成功',
      });
      clipboard.destroy();
    });

    clipboard.on('error', () => {
      message.open({
        type: 'error',
        content: '拷贝失败',
      });
      clipboard.destroy();
    });
  };
  const MarkersSelect = [
    {
      label: (
        <div className="zancaiHandleTag">
          <LikeFilled style={{ color: '#60D9A4' }} />赞
        </div>
      ),
      key: '1',
    },
    {
      label: (
        <div className="zancaiHandleTag">
          <DislikeFilled style={{ color: '#F57070' }} />踩
        </div>
      ),
      key: '2',
    },
  ];
  const zancaiHandleClick = async (v: any, item: any) => {
    let type = Number(v.key);
    let zanTxt = '谢谢您的认可，我会继续努力的！';
    // let caiTxt = '收到您的反馈，我会总结经验，努力改进的。';
    // let reason = type === 1 ? zanTxt : caiTxt;
    let body = {
      query_string: item?.sentence,
      query_result: item?.keyword,
      source: '小模型',
      type,
      reason_ids: [],
    };
    //赞的直接调用接口 显示反馈的文案 踩的需要显示反馈列表和将输入框变为踩模式
    if (type === 1) {
      updateState({
        robotLoading: true,
      });
      const res = await search_feedback(body);
      if (res.code === 0) {
        let zancaiTip = {
          key: nanoid(),
          type: 'userZanCai',
          data: {
            type,
            reason: '这个内容写得很好，值得表扬！',
            target_content: item.sentence,
            range: null,
          },
        };

        setTimeout(() => {
          setAILogs((prev: any) => [...prev, zancaiTip]);
          updateState({
            robotLoading: false,
          });
        }, 500);
        setTimeout(() => {
          let systemTxtRecover = {
            key: nanoid(),
            type: 'systemTxtRecover',
            spend: 30,
            data: [zanTxt],
          };
          setAILogs((prev: any) => [...prev, systemTxtRecover]);
        }, 1000);
      } else {
        updateState({
          robotLoading: false,
        });
        message.open({
          type: 'error',
          content: res.msg,
        });
      }
    } else {
      //踩的需要输入框变为踩模式
      let caiTip = {
        key: nanoid(),
        type: 'feedbackReasons',
        data: {
          ...item,
          query_string: item?.sentence,
          query_result: item?.keyword,
          source: '小模型',
          type,
        },
      };
      setTimeout(() => {
        setAILogs((prev: any) => [...prev, caiTip]);
        //显示点踩的输入框
        updateState({
          curOperationType: {
            type: 'caiFeedback',
            data: {
              ...item,
              query_string: item?.sentence,
              query_result: item?.keyword,
              source: '小模型',
              type,
              text: item?.sentence,
            },
          },
        });
      }, 500);
    }
  };

  //匹配文章内容 替换成样式
  const articleMatch = (data: any) => {
    if (data) {
      let sentence = data.sentence || '';
      let main_body = data.main_body || '';
      //main_body匹配sentence 将它换成高亮样式
      // 转义 sentence 中的特殊字符
      let escapedSentence = sentence.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');

      // 构建安全的正则表达式
      let regex = new RegExp('(' + escapedSentence + ')', 'gi');
      // 替换为带有高亮样式的文本
      let replacementText = '<span class="highlightCon">$1</span>';
      let mainBody = main_body.replace(regex, replacementText);

      return mainBody;
    } else {
      return '';
    }
  };

  return (
    <>
      {list.length > 0 &&
        list.map((item: any) => (
          <div className="sourceWrap" key={item.key}>
            <div className="sourceBox" key={item.key}>
              <div
                className="sourceTopBox"
                dangerouslySetInnerHTML={{
                  __html: item.sentence,
                }}
              ></div>

              <div className="sourceBottomBox">
                <div className="sourceBottomBox-avatar">
                  <img src={ROBOT_AVATAR} width={22} height={22} alt="" />
                </div>
                <div className="sourceBottomBox-hd">由横琴部门知识运算回答</div>
                {/* {item?.main_body?.length > 50 && ( */}
                <div
                  className="sourceBottomBox-bd"
                  onClick={() => {
                    lookSource(item);
                  }}
                >
                  查看原文
                </div>
                {/* )} */}
              </div>
            </div>
            <div className="copy-sourceBox">
              <Tooltip
                defaultOpen={false}
                trigger={['hover']}
                color="blue"
                title="拷贝文案"
                placement="topLeft"
              >
                <Button
                  className="copy-button"
                  onClick={() => {
                    copyText(item);
                  }}
                  shape="circle"
                >
                  <img className="avatar" src={copyicon} height={32} width={32} />
                </Button>
              </Tooltip>
              <Dropdown
                placement="bottom"
                menu={{ items: MarkersSelect, onClick: (v) => zancaiHandleClick(v, item) }}
                className=""
              >
                <img className="avatar" src={zancaiicon} height={32} width={32} />
              </Dropdown>
            </div>
          </div>
        ))}
      <Modal
        centered
        className="articleSourceModal"
        // title={currentDemo?.title}
        title={[
          <div className="" key={nanoid()}>
            <div className="articleDetailTitleBox">
              {currentDemo?.domain &&
                currentDemo?.domain?.length > 0 &&
                currentDemo?.domain?.map((item2) => {
                  return (
                    <Tag key={item2.id} color="blue">
                      {item2.name}
                    </Tag>
                  );
                })}
              {currentDemo?.title && currentDemo?.title.length > 0 && (
                <div className="articleDetailTitle">{currentDemo?.title}</div>
              )}
            </div>
          </div>,
        ]}
        open={isDemoOpen}
        footer={[
          <div className="bootomInfo" key={nanoid()}>
            {currentDemo?.released_at && (
              <span className="bootomInfo-hd">
                发布于 {dayjs(currentDemo?.released_at).format('YYYY/MM/DD')}
              </span>
            )}
            <span className="bootomInfo-bd" style={{ color: '#397bff' }}>
              {currentDemo?.source}
            </span>
          </div>,
        ]}
        onCancel={demoModalCancel}
        width={650}
      >
        <div className="modalBodyRef" ref={modalBodyRef}>
          <div dangerouslySetInnerHTML={{ __html: articleMatch(currentDemo) }}></div>
        </div>
      </Modal>
    </>
  );
};

// export default MiniModelArticle;
export default connect(({ conversation }) => ({ conversation }))(MiniModelArticle);
